/**
 * This node script naively takes `jsx-h.d.ts` as source and writes a new `jsx.d.ts`:
 *
 * - Takes `jsx-h.d.ts` as source
 * - Removes `FunctionElement` from `type Element`
 * - Strips `FunctionMaybe` from elements attributes
 * - Writes a new `jsx.d.ts`
 *
 * @see https://github.com/ryansolid/dom-expressions/issues/408
 */

import fs from "fs";
import { execSync as $ } from "child_process";

process.chdir("packages/dom-expressions/src");

// ensures source is always pretty printed at commit and free of errors

$(`prettier "./jsx-h.d.ts" --write`);

// copy source to temp file

fs.copyFileSync("./jsx-h.d.ts", "./jsx-h.temp.d.ts");

// make each property a one liner in temp file

$(`prettier "./jsx-h.temp.d.ts" --write --no-editorconfig --print-width 100000`);

// read source

const source = fs.readFileSync("./jsx-h.temp.d.ts").toString().split("\n");

// remove `-h` types

for (let i = 0; i < source.length; i++) {
	const line = source[i].trim();

	if (line.startsWith("type Element")) {
		// remove `| FunctionElement` from 'type Element'
		source[i] = line.replace("| FunctionElement", "");
	} else if (!line.startsWith("type FunctionMaybe") && line.includes("FunctionMaybe")) {
		// unwrap `FunctionMaybe'
		source[i] = line.replace(/: FunctionMaybe<([^>]+)>;$/, ": $1");
	}
}

// write result

const banner = `/**
	THIS FILE IS GENERATED BY \`./jsx-update.mjs\`.
	PLEASE UPDATE \`jsx-h.d.ts\` INSTEAD AND RUN \`pnpm jsx-sync-types\`.
*/

`;
fs.writeFileSync("./jsx.d.ts", banner + source.join("\n"));

// reformat file

$(`prettier "./jsx.d.ts" --write`);

// discard temporal file

fs.unlink("./jsx-h.temp.d.ts", () => {});
